package ru.eas.packer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author aesipov
 */
public class PackService {

    public PackService(Solution firstSolution) {
        this.bestSolution = firstSolution;
    }

    private Solution bestSolution = new Solution();

    public void process(Solution solution, Queue<Box> boxes) {
        if (boxes.isEmpty()) {
            stateCompetition(solution);
            return;
        }
        Box box = boxes.poll();
        List<Solution> nextSolutions = getNextStates(solution, box);
        if (!nextSolutions.isEmpty()) {
            for (Solution nextSolution : nextSolutions) {
                process(nextSolution, new LinkedList<Box>(boxes));
            }
        } else {
            stateCompetition(solution);
        }
    }

    private List<Solution> getNextStates(Solution solution, Box box) {
        List<Solution> result = new ArrayList<Solution>();
        for (Box rotatedBox : box.getAllRotations()) {
            for (Point point : solution.getPoints()) {
                PositionedBox positionedBox = new PositionedBox(rotatedBox, point);
                if (solution.validateNewBox(positionedBox)) {
                    result.add(solution.newSolution(positionedBox));
                }
            }
        }
        return result;
    }

    private void stateCompetition(Solution solution) {
        if (solution.getQuality() > bestSolution.getQuality()) {
            bestSolution = solution;
        }
    }
}
